"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/10/24
 */
import * as React from 'react'
import {autoSize, commonProps, commonStyles} from "../../assets/styles/common";
import NavRightButton from "../../component/RightButton";

const {connect} = require('react-redux');

const {View, TouchableOpacity, FlatList, DeviceEventEmitter} = require('react-native');
import SearchBar from "../../component/SearchBar";

const NavigationBar = require('react-native-navbar').default;
const {Actions} = require("react-native-router-flux");
import MyText from "../../component/MyText";
import Colors from "../../assets/styles/Colors";
import Line from "../../component/Line";
import {SCREEN_WIDTH} from "../../constant";
import MyIcon from "../../component/icon";
import ReserveRoomItem from "../../component/ReserveRoomItem";
import {WorkSpacePage} from "../../interface/router";
import {TimeAreaPickerResponse} from "../../component/index";
import constant from "../../utils/constant";
import T from "../../utils/T";

const moment = require("moment");

const {DatePicker} = require('antd-mobile');

class ReservePage extends React.Component<WorkSpacePage, any> {

    _scrollView: any;

    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            currentTab: 0,
            visible: false,
            dpValue: new Date(),
            collapsed: false,
        };
    }


    componentDidMount(): void {
        this.onRefresh();
        DeviceEventEmitter.addListener(constant.noticeKeyOfTimeAreaFocus,_=>{
            // console.log('1',this._scrollView);
        });
        DeviceEventEmitter.addListener(constant.noticeKeyOfTimeAreaUnFocus,_=>{
            // console.log('2',this._scrollView);
        });
    }


    componentWillUnmount(): void {
        DeviceEventEmitter.removeListener(constant.noticeKeyOfTimeAreaFocus);
        DeviceEventEmitter.removeListener(constant.noticeKeyOfTimeAreaUnFocus);
    }

    onRefresh = () => {
        this.props.dispatch({
            type: 'room/fetchList',
            payload: {pi: 1, ps: 5}
        })
    };


    onEndReached = () => {
        if (this.props.room.list) {
            if (!this.props.room.list.last) {
                this.props.dispatch({
                    type: 'room/fetchList',
                    payload: {pi: this.props.room.list.number + 2, ps: 5, loadmore: true}
                })
            }
        } else {
            this.onRefresh();
        }
    };


    onPressNextStep = (item, selectDate: TimeAreaPickerResponse) => {
        Actions.confirmReserve({selectedRoom: item, selectDate, timeArea: selectDate.timeArea})
    };

    changeTab = (currentTab) => {
        const visible = currentTab === 2;
        let now = moment();
        let dpValue;
        if (currentTab === 1) {
            now.add(1, 'day');
        }
        dpValue = now.toDate();
        this.setState({currentTab, visible, dpValue});
    };


    renderListHeaderComponent = () => {
        return (
            <TouchableOpacity style={{backgroundColor: Colors.Clear, paddingVertical: 10}}
                              onPress={Actions.reserveWorkSpace}>
                <View style={[commonStyles.flexRow, {
                    justifyContent: 'space-between',
                    padding: 10,
                    backgroundColor: Colors.White
                }]}>
                    <MyText>预定工作场地</MyText>
                    <MyIcon name={'icon-iconfontyoujiantou'} color={Colors.Black}/>
                </View>
            </TouchableOpacity>

        )
    };

    renderItem = ({item}) => {

        let now = moment(this.state.dpValue);
        let nowDate = now.toDate();
        return <ReserveRoomItem item={item}
                                date={nowDate}
                                collapsed={true}
                                identifier={item.id}
                                onNextStepPress={this.onPressNextStep.bind(this, item)}
                                haveNextStep={true}/>
    };

    render() {
        let text = '选择日期';
        return (
            <View style={commonStyles.container}>
                <NavigationBar {...commonProps.navBar}
                               title={<SearchBar placeholder='探索会员圈'
                                                 rightButtonWidth={0}
                                                 editable={false}
                                                 onPress={Actions.search}/>}
                />

                <View style={[commonStyles.flexRow, {backgroundColor: Colors.Primary}]}>
                    {[T('Today'), T('Tomorrow'), text].map((text, index) => {
                        return (
                            <TouchableOpacity key={index} style={[commonStyles.flex1, {
                                height: autoSize(49)
                            }]} onPress={this.changeTab.bind(this, index)}>
                                <View style={[commonStyles.flex1, commonStyles.centerVH]}>
                                    <MyText
                                        color={index === this.state.currentTab ? Colors.Active : Colors.SubTitle}>{text}</MyText>
                                </View>
                                {index === this.state.currentTab ?
                                    <Line width={autoSize(SCREEN_WIDTH / 3)} height={4} color={Colors.Active}/> : null}
                            </TouchableOpacity>
                        )
                    })}
                </View>


                <FlatList data={this.props.room.list ? this.props.room.list.content : []}
                          ListHeaderComponent={this.renderListHeaderComponent}
                          extraData={this.props}
                          keyExtractor={(item, index) => index}
                          onRefresh={this.onRefresh}
                          refreshing={this.props.room.loading}
                          onEndReached={this.onEndReached}
                          onEndReachedThreshold={1}
                          ref={_scrollView => this._scrollView = _scrollView}
                          ItemSeparatorComponent={() => <Line height={10}/>}
                          renderItem={this.renderItem}
                />


                <DatePicker
                    visible={this.state.visible}
                    value={this.state.dpValue}
                    minDate={moment().toDate()}
                    onOk={date => {
                        let currentTab = this.state.currentTab;
                        if (moment(date).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')) {
                            currentTab = 0;
                        } else if (moment(date).format('YYYY-MM') === moment().format('YYYY-MM')) {
                            if (moment(date).day() - moment().day() === 1) {
                                currentTab = 1;
                            }
                        }
                        this.setState({dpValue: date, visible: false, currentTab});
                    }}
                    onDismiss={() => this.setState({visible: false})}
                />
            </View>
        );
    }
}


export default connect(
    ({auth, room}) => ({auth, room})
)(ReservePage);


